<template>
  <div class="user-center">
    <el-card>
      <h2>个人中心</h2>
      <el-form :model="user" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="user.username" disabled />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="user.realname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="user.phone" />
        </el-form-item>
        <el-form-item label="账户余额">
          <el-input v-model="user.account" disabled />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-tag v-if="isMember" type="success">会员</el-tag>
          <el-tag v-else type="info">临时用户</el-tag>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUser" :loading="loading">保存信息</el-button>
          <el-button v-if="!isMember" type="warning" @click="upgradeToMember" :loading="loading">申请会员</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="msg" :title="msg" type="success" show-icon style="margin-top:10px;" />
      <el-button type="danger" @click="handleLogout" style="margin-top:20px;">退出登录</el-button>
    </el-card>
  </div>
</template>

<script>
import api from '@/api';
export default {
  data() {
    return {
      user: {},
      isMember: false,
      loading: false,
      msg: ''
    };
  },
  async created() {
    this.loading = true;
    try {
      const res = await api.get('/user/info');
      this.user = res;
      this.isMember = res.usertype === 'MEMBER';
    } catch (e) {
      this.msg = '获取用户信息失败';
    }
    this.loading = false;
  },
  methods: {
    async upgradeToMember() {
      this.loading = true;
      try {
        await api.post('/user/apply-member');
        this.msg = '会员申请成功，请等待审核';
        this.isMember = true;
      } catch (e) {
        this.msg = '会员申请失败';
      }
      this.loading = false;
    },
    async updateUser() {
      this.loading = true;
      try {
        await api.post('/user/update', this.user);
        this.msg = '信息更新成功';
      } catch (e) {
        this.msg = '信息更新失败';
      }
      this.loading = false;
    }
  }
};
</script>

<style scoped>
.user-center { max-width: 500px; margin: 40px auto; }
</style>
